﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using OpenTwitter.SDK;

namespace TaoTaoKeForQqWeibo
{
    public partial class MainForm : Form
    {
        bool fetchingItems = false;
        public bool IsFetchingItems
        {
            set
            {
                if (value)
                {
                    this.label1.Text = "Fetching";
                }

                fetchingItems = value;
                DataObj.WeatherFetch = value;
            }
            get
            {
                return fetchingItems;
            }
        }

        public Thread FetchThread { get; set; }

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //Setting.Default.Reset();
            //Setting.Default.Save();

            //加入热键
            HotKeyControl.RegisterHotKey(this.Handle,
                HotKeyControl.HotKeyId,
                HotKeyControl.ControlKey,
                HotKeyControl.HotKey);
        }

        private void btnFetchItems_Click(object sender, EventArgs e)
        {
            this.IsFetchingItems = !this.IsFetchingItems;

            if (this.IsFetchingItems)
            {
                ThreadPool.QueueUserWorkItem((obj) =>
                    {
                        this.FetchThread = Thread.CurrentThread;

                        DataObj.FetchItems((item) =>
                        {
                            if (this.lbxItemsFetched.InvokeRequired)
                            {
                                this.lbxItemsFetched.Invoke(new Action(() =>
                                {
                                    if (this.lbxItemsFetched.Items.Count > 400)
                                    {
                                        this.lbxItemsFetched.Items.Clear();
                                    }

                                    this.lbxItemsFetched.Items.Add(item.title);
                                }));
                            }
                        });

                        this.label1.Invoke(new Action(() =>
                        {
                            this.label1.Text = "Stoped";
                        }));
                    });
            }
        }

        private void btnSendQqWeiBo_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(TencentWeibo.Oauth.Token))
            {
                MessageBox.Show("Get Token First!");
                return;
            }

            TencentWeibo.WeatherSending = !TencentWeibo.WeatherSending;

            this.btnSendQqWeiBo.Text = "sending";

            if (TencentWeibo.WeatherSending)
            {
                ThreadPool.QueueUserWorkItem((obj) =>
                {
                    TencentWeibo.sendweibo(() =>
                    {
                        if (this.btnSendQqWeiBo.InvokeRequired)
                        {
                            this.btnSendQqWeiBo.Invoke(new Action(() =>
                            {
                                this.btnSendQqWeiBo.Text = "Send";
                            }));
                        }
                    });
                });
            }
        }

        private void btnGetToken_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(TencentWeibo.Oauth.Token))
            {
                //获取请求Token
                if (TencentWeibo.Oauth.GetRequestToken(null))
                {
                    this.webBrowser1.Navigate(
                        "https://open.t.qq.com/cgi-bin/authorize?oauth_token=" + TencentWeibo.Oauth.Token);
                }
            }
        }

        private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            string[] querys = e.Url.Query.Replace("?", string.Empty).Split('&');
            Hashtable table = new Hashtable();
            foreach (var item in querys)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    string[] items = item.Split('=');
                    table.Add(items[0], items[1]);
                }
            }
            if (table.Contains("vcode"))
            {
                string verifier = table["vcode"].ToString();
                AuthorizedUser user;
                if (TencentWeibo.Oauth.GetAccessToken(verifier, out user))
                {
                    Console.WriteLine("获取Access Token成功。值如下：");
                    Console.WriteLine("TokenKey={0}", TencentWeibo.Oauth.Token);
                    Console.WriteLine("TokenSecret={0}", TencentWeibo.Oauth.TokenSecret);
                    Console.WriteLine("微博帐 Uid={0}, Name={1}", user.Uid, user.Name);
                    this.lblUser.Text = user.Name;


                }
                else
                {
                    Console.WriteLine("获取Access Token时出错，错误信息： {0}", TencentWeibo.Oauth.LastError);
                }
            }
        }

        private void btnResetNum_Click(object sender, EventArgs e)
        {
            Setting.Default.Reset();
            Setting.Default.Save();
        }

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case 0x0312:
                    if (m.WParam.ToInt32() == HotKeyControl.HotKeyId)
                    {
                        if (this.Visible)
                        {
                            this.Hide();
                        }
                        else
                        {
                            this.Show();
                        }
                    }
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
        }
    }
}
